package com.woniuxy.oss.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.bean.ResponseResult;
import com.woniuxy.commons.enums.ResponseStatus;
import com.woniuxy.oss.bean.UploadResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @author: 15489  <br/>
 * Date: 2022/3/31:11:25  <br/>
 * Description:
 */

@RestController
@RequestMapping("/file")
public class FileController {
    @Resource  //注入阿里云的客户端
    private OSSClient ossClient;
    private  static final String BUCKET_NAME="zhuhongjin";
//    url前缀
    private  static  final  String URL_PREFIX="https://zhuhongjin.oss-cn-chengdu.aliyuncs.com";

    @PostMapping("/upload")
    public ResponseResult<UploadResult> upload(MultipartFile file){
//        1:获取文件的名字
        String fileName=file.getOriginalFilename();

        try {
            //        2：获取文件的流对象
            InputStream inputStream = file.getInputStream();
// 3:利用阿里云客户端上传文件
//          参数一 ：通的名字  参数二 文件名 参数三 流对象
            ossClient.putObject(BUCKET_NAME,fileName,inputStream);

//           4：设置文件过期时间
            Date date=new Date(new Date().getTime()+1000*60*60*24*30);

//            5 上传文件 指定过期时间 返回文件uri
            URL url = ossClient.generatePresignedUrl(BUCKET_NAME, fileName, date);
            System.out.println(url.getPath()+"1111111111111111111111111");
//            封装结果返回
            UploadResult result=new UploadResult();
            result.setFileName(fileName);
            result.setUrl(URL_PREFIX+url.getPath());

           ResponseResult<UploadResult> responseResult=new ResponseResult<>();
           responseResult.setCode(200);
           responseResult.setMessage("上传成功");
           responseResult.setStatus(ResponseStatus.SUCCESS);
           responseResult.setData(result);
           return responseResult;

        }catch (Exception e){
            e.printStackTrace();
        }

        return null;




    }
    @DeleteMapping("/del/{fileName}")
    public ResponseResult<Object> del(@PathVariable("fileName") String fileName){
        ossClient.deleteObject(BUCKET_NAME,fileName);
//
        ResponseResult<Object> result=new ResponseResult<>();
        result.setMessage("删除成功");
        result.setCode(200);
        result.setStatus(ResponseStatus.SUCCESS);
        return result;
    }
}
